// components/withAuth.js
import {useEffect, useState} from 'react';
import { useRouter } from 'next/router';

const withAuth = (WrappedComponent, allowedRoles) => {
    return (props) => {
        const router = useRouter();
        const [userRole, setUserRole] = useState();

        useEffect(() => {
            const userInfo = JSON.parse(localStorage.getItem('userInfo'));
            setUserRole(userInfo ? userInfo.role : null);
        }, []);

        useEffect(() => {
            if (userRole === undefined) return; // 如果userRole未定义，不执行操作
            console.log('角色', userRole);
            // 检查用户角色是否在允许的角色列表中
            if (!allowedRoles.includes(userRole)) {
                router.push('/');
            }
        }, [userRole, router]); // 第二个useEffect仅当userRole改变时运行

        return <WrappedComponent {...props} />;
    };
};

export default withAuth;
